// @(#)inifile.cc
// Time-stamp: <2009-01-13 17:30:19 lancer>
// Copyright 2008 Julian Qian
// Author: root@localhost.localdomain
// Version: $Id: inifile.cc,v 0.0 2008/11/18 14:00:36 root Exp $
// Keywords: 

#include "inifile.hh"
#include "log.hh"

using namespace std;

const char*const MIDDLESTRING = "_____***_______";

struct analyzeini{
    string strsect;
    strMap *pmap;
    analyzeini(strMap & strmap):pmap(&strmap){}
    void operator()( const string & strini){
        int first =strini.find('[');
        int last = strini.rfind(']');
        if( first != string::npos && last != string::npos && first != last+1){
            strsect = strini.substr(first+1,last-first-1);
            return ;
        }
        if(strsect.empty())
            return ;
        if((first=strini.find('='))== string::npos)
            return ;
        string strtmp1= strini.substr(0,first);
        string strtmp2=strini.substr(first+1, string::npos);
        first= strtmp1.find_first_not_of(" \t");
        last = strtmp1.find_last_not_of(" \t");
        if(first == string::npos || last == string::npos)
            return ;
        string strkey = strtmp1.substr(first, last-first+1);
        first = strtmp2.find_first_not_of(" \t");
        if(((last = strtmp2.find("\t#", first )) != string::npos) ||
           ((last = strtmp2.find(" #", first )) != string::npos) ||
           ((last = strtmp2.find("\t//", first )) != string::npos)||
           ((last = strtmp2.find(" //", first )) != string::npos)){
            strtmp2 = strtmp2.substr(0, last-first);
        }
        last = strtmp2.find_last_not_of(" \t");
        if(first == string::npos || last == string::npos)
            return ;
        string value = strtmp2.substr(first, last-first+1);
        string mapkey = strsect + MIDDLESTRING;
        mapkey += strkey;
        (*pmap)[mapkey]=value;
        return ;
    }
};

string
IniFile::read(const char*psect, const char*pkey){
    string mapkey = psect;
    mapkey += MIDDLESTRING;
    mapkey += pkey;
    strMapIt it = c_inimap.find(mapkey);
    if(it == c_inimap.end())
        return "";
    else
        return it->second;
}

bool
IniFile::do_open(const char* pinipath){
    ifstream fin(pinipath);
    if(!fin.is_open())
        return false;
    vector<string> strvect;
    while(!fin.eof())
    {
        string inbuf;
        getline(fin, inbuf,'\n');
        strvect.push_back(inbuf);
    }
    if(strvect.empty())
        return false;
    for_each(strvect.begin(), strvect.end(), analyzeini(c_inimap));
    return !c_inimap.empty();
}


Config* Config::_theConfig = NULL;

Config*
Config::theConfig(const char* conf){
    if(NULL == _theConfig){
        _theConfig = new Config(conf);
    }
    return _theConfig;    
}

void
Config::endConfig(){
    delete _theConfig;
}

Config::Config(const char* conf){
    open(conf);
}

Config::~Config(){
}
